package com.easycarebn.request.data;

import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import android.text.TextUtils;

import com.android.volley.VolleyError;

public class ErrorResponse extends DataItemResponse {
    private String message;

    public String getMessage() {
        return message;
    }

    public static ErrorResponse newInStance(VolleyError error) {
        ErrorResponse errResponse = new ErrorResponse();
        if(error == null) {
            return errResponse;
        }
        String data = error.getMessage();
        System.out.println("Error: " + data);
        if(TextUtils.isEmpty(data)) {
            return errResponse;
        }
        JSONObject json;
        int code = 0;
        StringBuilder builder = new StringBuilder();
        try {
            json = new JSONObject(data);
            code = json.getInt("code");
            Object msg = json.get("errors");
            if(msg != null && msg instanceof JSONObject) {
                JSONObject jsonErrors = json.getJSONObject("errors");
                if(jsonErrors == null) {
                    return errResponse;
                }
                Iterator<String> it = jsonErrors.keys();
                if(it == null) {
                    return errResponse;
                }
                String key;
                while (it.hasNext()) {
                    key = it.next();
                    try {
                        builder.append(jsonErrors.get(key)).append("\n");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            } else {
                    builder.append(msg);
            }
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        errResponse.code = code;
        errResponse.message = builder.toString();
        return errResponse;
    }
}
